package logger

import (
	"context"
	"database/sql"
	"fmt"
	"time"

	_ "github.com/go-sql-driver/mysql"
)

func NewManticoreSql(ctx context.Context, dsn, indexName string) *ManticoreSql {
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return nil
	}

	if err := db.Ping(); err != nil {
		return nil
	}

	return &ManticoreSql{
		ctx:       ctx,
		db:        db,
		indexName: indexName,
	}
}

type ManticoreSql struct {
	ctx       context.Context
	db        *sql.DB
	indexName string
}

func (r *ManticoreSql) Log(message string) error {
	timestamp := time.Now().Unix()

	query := fmt.Sprintf("INSERT INTO %s (message, timestamp) VALUES (?, ?)", r.indexName)
	_, err := r.db.Exec(query, message, timestamp)
	if err != nil {
		return fmt.Errorf("failed to log to Manticore: %v", err)
	}

	return nil
}
